# File instantiates all sections in the FeedView

from pypump.models.image import Image
from pypump.models.comment import Comment
from pypump.exception import PyPumpException
from kivy.metrics import sp

import datetime
import pytz


# default dictionary for a mediagoblin feedview
def mg_activity_dict(activity, index):
    activity_list = []
    activity_list.append(build_header(activity, index))
    activity_list.append(build_main_content(activity, index))
    activity_list.append(build_title(activity, index))
    activity_list.append(build_description(activity, index))
    activity_list.append(build_view_comments_button(activity, index))
    activity_list.extend(build_comments(activity, index))
    activity_list.append(build_padding())
    return activity_list


# default dictionary for a pumpity feedview
def pumpity_activity_dict(self, activity, index):
    pass


def build_header(activity, index):
    def get_published_time():
        published = activity.published
        now = datetime.datetime.now(pytz.UTC)
        time_since_post = (now - published)
        if time_since_post.days > 365:
            return '{0} y'.format(time_since_post.days / 365)
        elif time_since_post.days > 30:
            return '{0} m'.format(time_since_post.days / 30)
        elif time_since_post.days > 7:
            return '{0} w'.format(time_since_post.days / 7)
        elif time_since_post.days > 0:
            return '{0} d'.format(time_since_post.days)
        elif time_since_post.seconds / (60 ** 2) > 0:
            return '{0} h'.format(time_since_post.seconds / (60 ** 2))
        elif time_since_post.seconds / 60 > 0:
            return '{0} m'.format(time_since_post.seconds / 60)
        else:
            return 'moments ago'

    return dict([
        ('viewclass', 'ActivityHeader'),
        ('index', index),
        ('actor', unicode(activity.actor.webfinger)),
        ('post_time', get_published_time())])


def build_main_content(activity, index):
    return parse_activity_types(activity, index)


# TODO name: activitybuttons -> actionbar
def build_action_bar(activity, index):
    return dict([
        ('viewclass', 'ActivityButtons'),
        ('index', index)])


def build_title(activity, index):
    def display_title(activity):
        try:
            title = activity.obj.display_name
            if title is None:
                title = activity.content
            try:
                return unicode(title)
            except UnicodeEncodeError:
                return 'unicode error'
        except AttributeError:
            return 'no description'

    return dict([
        ('viewclass', 'ActivityTitle'),
        ('text', display_title(activity))])


def build_description(activity, index):
    def display_description(activity):
        try:
            actor = activity.obj.author.username
            description = activity.obj.content
            if description is None:
                description = activity.content.split(' ', 2)[2]
            try:
                return unicode('[ref=actor][color=86D4B1]{0}[/color][/ref] {1}'.format(
                    unicode(actor), unicode(description)))
            except UnicodeEncodeError:
                return 'no description'
                # return 'unicode error'
        except AttributeError:
            return 'no description'

    return dict([
        ('viewclass', 'Description'),
        ('text', display_description(activity)),
        ('actor', unicode(activity.actor.webfinger)),
        ('height', sp(50)),
        ('index', index),
        ('markup', True)])


def build_view_comments_button(activity, index):
    try:
        count = activity.obj.comments.total_items
        # for some reason, removing the if/else statements cause an error
        if count == 0:
            text = 'no comments yet, be the first!'
        elif count == 1:
            text = 'view this comment'
        else:
            text = 'view all {0} comments'.format(count)
        return dict([
            ("viewclass", "ViewCommentsButton"),
            ('button_text', text),
            ('height', sp(20)),
            ('count', count),
            ('activity_id', unicode(activity.id)),
            ("index", index)])
    except KeyError, e:
        print ('build_view_comments_button: {0}'.format(e))


def build_comments(activity, index):

    def build_comment_dict(author, content):
        comment = unicode('[ref=actor][color=86D4B1]{0}[/color][/ref] {1}'.format(
            unicode(author.username), unicode(content)))
        return dict([
            ("viewclass", "CommentSnapshot"),
            ('actor', unicode(author)),
            ("text", comment),
            ("height", sp(20)),
            ("index", index),
            ("markup", True)])
    comment_array = []
    comment_index = 0
    try:
        for comment in activity.obj.comments[:3]:
            author = comment.author
            content = comment.content
            comment_array.append(build_comment_dict(author, content))
            comment_index += 1
    except (AttributeError, UnicodeEncodeError, PyPumpException), e:
        print('display_comments: {0}'.format(e))
    return comment_array


def parse_activity_types(activity, index):
    if isinstance(activity.obj, Image):
        return is_image_activity(activity, index)
# TODO verifiy whether mediagoblin uses notes or comments
    elif isinstance(activity.obj, Comment):
        return is_comment_activity(activity, index)
    else:
        return is_video_activity(activity, index)


def is_image_activity(activity, index):
    try:
        url = activity.obj.thumbnail.url
        prepend, thumbnail, ext = url.rsplit('.', 2)
        if ext == 'gif':
            url = '{0}.{1}'.format(prepend, ext)
        else:
            url = '{0}.medium.{1}'.format(prepend, ext)
        return dict([
            ("viewclass", "ActivityImage"),
            ("height", sp(350)),
            ("source", url)])
    except (AttributeError, Exception), e:
        print ('image failed: {0}'.format(e))
        return dict([
            ("viewclass", "ActivityVideo"),
            ("height", sp(300)),
            ("text", e)])


def is_comment_activity(activity, index):
    try:
        comment = unicode(activity.obj.content)
    except (AttributeError, Exception), e:
        print ('is_comment_activity_: {0}'.format(e))
        comment = 'failed to pull comment'
    return dict([
        ("viewclass", "ActivityComment"),
        ("height", sp(300)),
        ("comment", comment)])


def is_video_activity(activity, index):
    else_text = 'cannot display audio/video yet'
    return dict([
        ("viewclass", "ActivityVideo"),
        ("height", sp(300)),
        ("text", else_text)])


def build_padding():
    return dict([
        ("viewclass", "BoxLayout"),
        ("height", sp(40))])
